﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using NUnit.Framework;

namespace Chambills.Present.Validation.Tests
{
    [TestFixture, RequiresSTA]
    public class BrokenBindingNotifierFixture
    {
        private BrokenBindingNotifier notifier;
        private StackPanel parent;
        private BindingExpressionBase binding;
        private const string BindingPath = "Text";

        [SetUp]
        public void Setup()
        {
            notifier = new BrokenBindingNotifier { PropertiesWithBrokenBindings = new List<string>() };
            parent = new StackPanel();
            parent.Children.Add(notifier);
            binding = BindingOperations.SetBinding(parent, FrameworkElement.TagProperty, new ValidatedBinding(BindingPath));


        }

        [Test]
        public void PropertiesWithBrokenBindingsContainBrokenPropertyNameAfterError()
        {

            RaiseError();
            CollectionAssert.Contains(notifier.PropertiesWithBrokenBindings, BindingPath);
        }


        [Test]
        public void PropertiesWithBrokenBindingsDoesNotContainBrokenPropertyNameWhenErrorFixed()
        {

            RaiseError();
            RemoveError();

            CollectionAssert.DoesNotContain(notifier.PropertiesWithBrokenBindings, BindingPath);
        }

        [Test(Description = "These are handled by the ViewModel")]
        public void ShouldIgnoreNonExceptionalValidations()
        {

            RaiseError(new DataErrorValidationRule());
            CollectionAssert.IsEmpty(notifier.PropertiesWithBrokenBindings);
        }

        private void RaiseError()
        {
           RaiseError(new ExceptionValidationRule());
        }

        private void RaiseError(ValidationRule rule)
        {
            System.Windows.Controls.Validation.MarkInvalid(binding, new ValidationError(rule, binding));
        }


        private void RemoveError()
        {
            System.Windows.Controls.Validation.ClearInvalid(binding);
        }

    }
}
